<!--
  文件描述：
  创建时间：2023/9/7 17:33
  创建人：二
-->
<template>
  <m-drawer
    :title="title"
    :loading="loading"
    :visible="visible"
    :show-close="true"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="roles">
        <el-tree
          ref="tree"
          :data="menuTreeData"
          :props="props"
          show-checkbox
          node-key="id"
          :expand-on-click-node="false"
          @check-change="handleCheckChange">
        </el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close()" :disabled="loading">取消</el-button>
      <el-button type="primary" @click="handleSubmit()" :loading="loading">保存</el-button>
    </template>
  </m-drawer>
</template>

<script>
export default {
  name: 'edit',
  props: {
    menuTreeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      type: '',
      visible: false,
      loading: false,
      form: {
        name: '',
        roles: []
      },
      rules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入角色名称' }
        ],
        roles: [
          { required: true, trigger: 'change', message: '请选择权限' }
        ]
      },
      props: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    title() {
      return this.type === 'add' ? '新增' : '编辑'
    }
  },
  methods: {
    // 打开弹窗
    open(data, type = 'add') {
      this.type = type;
      if(data) {
        this.form = this.mixinObjAssign(this.form, data);
      }
      this.visible = true;
    },
    // 关闭弹窗
    close() {
      this.resetForm();
      this.loading =false;
      this.visible = false;
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
    },
    // 提交
    handleSubmit() {
      this.$refs.form.validate( valid => {
        if (!valid) return false;
        console.log('form', this.form);
        this.mixinMessageBoxConfirm('是否提交保存?').then(({instance, done}) => {
          this.loading = true;
          setTimeout(() => {
            done();
            setTimeout(() => {
              instance.confirmButtonLoading = false;
              this.$message({
                type: 'success',
                message: '成功!'
              });
              this.close();
              this.$emit('success', this.type === 'add');
            }, 300);
          }, 2000);
        }).catch(() => {});
      });
    },
    handleCheckChange() {
      // 返回目前被选中的节点的 key所组成的数组
      let arr = this.$refs.tree.getCheckedKeys(); // 重点
      arr = arr.concat(
        // 返回目前半选中的节点的 key 所组成的数组
        this.$refs.tree.getHalfCheckedKeys() // 重点
      );
      this.form.roles = arr;
    }
  }
}
</script>

<style scoped>

</style>
